﻿using Sys.Common;
using Sys.Core.Dri;
using Sys.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Sys.Api.Dri
{
    public class StudentApi : BaseApi
    {
        public string Grid(int rows, int page, string search)
        {
            var entities = StudentBll.I.SortEntities;

            this.EntitiesFilter(search, ref entities);

            var list = StudentBll.I.EntitiesPage(entities, rows, page);
            return GetGrid(entities.Count(), list);
        }

        /// <summary>
        /// 实体过滤（根据查询条件）
        /// </summary>
        /// <param name="search"></param>
        /// <param name="entities"></param>
        private void EntitiesFilter(string search, ref IQueryable<DriStudent> entities)
        {
            //模糊检索学员信息
            if (!string.IsNullOrEmpty(search))
            {
                //T开头，代表搜索推荐人
                if (search.StartsWith("T"))
                {
                    search = search.Remove(0, 1);
                    entities = entities.Where(m => m.Recommender == search);
                }
                else
                {
                    //如果包含多个关键词
                    if (search.IndexOf(' ') >= 0)
                    {
                        List<string> searchList = search.Split(' ').ToList();
                        //学员编号、受理号、姓名、证件号、手机、申请类型（以结尾为准）
                        entities = entities.Where(m => searchList.Contains(m.Num) || searchList.Contains(m.AcceptingNum) || searchList.Contains(m.Name) || searchList.Contains(m.CertificateNum) || searchList.Contains(m.Mobile) || searchList.Contains(m.ApplyType));
                    }
                    //单关键词情况
                    else
                    {
                        //学员编号、受理号、姓名、证件号、手机、申请类型（以结尾为准）
                        entities = entities.Where(m => m.Num.Contains(search) || m.AcceptingNum.Contains(search) || m.Name.Contains(search) || m.CertificateNum.Contains(search) || m.Mobile.Contains(search) || m.ApplyType.EndsWith(search));
                    }
                }
            }
        }

        private void SearchEntities(IQueryable<DriStudent> entities, string search)
        {

        }

        public string Save(DriStudent model)
        {
            JsonMsg result = new JsonMsg();

            //判断证件号是否重复
            var isExistCertificateNum = StudentBll.I.IsExistCertificateNum(model.CertificateType, model.CertificateNum, model.ID);
            if (isExistCertificateNum)
            {
                result.Message = "证件号重复，请检查记录是否已存在!";
                return JsonHelper.ToJson(result);
            }

            //添加
            if (string.IsNullOrEmpty(model.ID))
            {
                result.Message = "添加成功!";

                model.ID = StringHelper.GetGuid();

                //model.IntSort = ButtonBll.I.MaxSort(m => m.IntSort);
                model.Num = StudentBll.I.NewNum;  //再次获取流水号，避免并发影响
                model.InsertTime = DateTime.Now;
                model.UpdateTime = model.InsertTime;
                model.IsVisible = true;  //默认开启
                result.Success = StudentBll.I.Insert(model) > 0;
            }
            //修改
            else
            {
                result.Message = "修改成功!";

                model.UpdateTime = DateTime.Now;
                result.Success = StudentBll.I.Update(model) > 0;
            }

            if (!result.Success) { result.Message = "操作失败!"; }

            return JsonHelper.ToJson(result);
        }

        public string Delete(string id)
        {
            JsonMsg result = new JsonMsg();

            result.Success = StudentBll.I.Delete(id) > 0;

            if (result.Success) { result.Message = "删除成功!"; }

            return JsonHelper.ToJson(result);
        }

        public string EnableOrDisable(string id, bool bit)
        {
            JsonMsg result = new JsonMsg();

            DriStudent model = StudentBll.I.GetByKey(id);

            if (model != null)
            {
                if (model.IsVisible != bit)
                {
                    model.IsVisible = bit;

                    result.Success = StudentBll.I.Update(model) > 0;

                    if (result.Success)
                    {
                        result.Message = bit ? "启用成功!" : "禁用成功!";
                    }
                }
                else
                {
                    result.Message = bit ? "已经是启用状态!" : "已经是禁用状态!";
                }
            }

            return JsonHelper.ToJson(result);
        }

        /// <summary>
        /// 添加相片
        /// </summary>
        /// <returns></returns>
        public string AddPhoto()
        {
            Hashtable hash = KindHelper.ImgUpload();

            if (Convert.ToInt32(hash["error"]) == 0)
            {
                HttpContext context = HttpContext.Current;

                int w = Convert.ToInt32(context.Request.QueryString["w"]);
                int h = Convert.ToInt32(context.Request.QueryString["h"]);

                string filename = hash["url"].ToString();

                string temppath = context.Server.MapPath("~/userfiles/temp/" + filename);
                string filepath = context.Server.MapPath("~/userfiles/student/");

                if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); }

                ThumNail.MakeThumNail(temppath, filepath + filename, w, h, TnType.Cut);

                System.IO.File.Delete(temppath);

                hash["url"] = filename;
            }

            return JsonHelper.ToJson(hash);
        }

        public string SavePayment(DriStuFinance model)
        {
            JsonMsg result = new JsonMsg();

            if (string.IsNullOrEmpty(model.ID))
            {
                result.Message = "缴费成功!";

                model.ID = StringHelper.GetGuid();

                model.InsertTime = DateTime.Now;
                result.Success = StuFinanceBll.I.Insert(model) > 0;
            }
            //else
            //{
            //    result.Message = "修改成功!";

            //    model.UpdateTime = DateTime.Now;
            //    result.Success = StudentBll.I.Update(model) > 0;
            //}

            if (!result.Success) { result.Message = "操作失败!"; }

            return JsonHelper.ToJson(result);
        }

        /// <summary>
        /// 导出
        /// </summary>
        public void Export()
        {
            var entities = StudentBll.I.SortEntities;
            //this.EntitiesFilter(search, ref entities);  //根据条件过滤
            var columns = new List<string[]>();
            columns.Add(new string[] { "Num", "学员编号" });
            columns.Add(new string[] { "AcceptingNum", "受理号" });
            columns.Add(new string[] { "Name", "姓名" });
            columns.Add(new string[] { "Sex", "性别" });
            columns.Add(new string[] { "CertificateType", "证件类型" });
            columns.Add(new string[] { "CertificateNum", "证件编号" });
            columns.Add(new string[] { "SignUpDate", "报名时间" });
            columns.Add(new string[] { "Registered", "户籍" });
            columns.Add(new string[] { "IsResidencePermit", "代办居住证" });
            //columns.Add(new string[] { "IsReturnCertificate", "已取回证件" });
            columns.Add(new string[] { "ApplyType", "申请类型" });
            columns.Add(new string[] { "Mobile", "手机" });
            columns.Add(new string[] { "Recommender", "推荐人" });
            columns.Add(new string[] { "IsArrears", "欠款" });
            columns.Add(new string[] { "ArrearsCondition", "欠款情况" });
            //columns.Add(new string[] { "Description", "备注" });
            columns.Add(new string[] { "IsVip", "VIP" });
            columns.Add(new string[] { "IsVisible", "启用" });
            NopiHelper.Export(columns, entities.ToList());
        }
    }
}
